//
//  GameConfirmController.m
//  ELife
//
//  Created by xiaozhi on 11-5-20.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "GameConfirmController.h"
#import "GameResultController.h"
#import "GameChargeParam.h"
#import "GameGoodsInfo.h"
#import "ELifeAppDelegate.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"

@implementation GameConfirmController
@synthesize gameNameLabel, gameAccountLabel, amountsLabel, pervalueLabel, 
serverLabel, shouldPayLabel;

- (void)initWithChargeParam:(GameChargeParam *)param goodsInfo:(GameGoodsInfo *)goodsInfo
{
    [gameNameLabel setText:goodsInfo.otherName];
    NSString *serverName = param.area;
    if (param.server != nil) {
        serverName = [serverName stringByAppendingFormat:@" - %@", param.server];
    }
    [serverLabel setText:serverName];
    [amountsLabel setText:param.goodsNum];
    [pervalueLabel setText:goodsInfo.pervalue];
    [gameAccountLabel setText:param.userId];
    [shouldPayLabel setText:param.money];
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil 
               bundle:(NSBundle *)nibBundleOrNil
          chargeParam:(GameChargeParam *)param
            goodsInfo:(GameGoodsInfo *)goodsInfo

{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _chargeParam = param;
        _goodsInfo = goodsInfo;
    }
    
    return self;
}

- (void)dealloc
{
    [gameNameLabel release];
    [gameAccountLabel release];
    [amountsLabel release];
    [serverLabel release];
    [pervalueLabel release];
    [amountsLabel release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor 
        = [[UIColor alloc]initWithPatternImage:[UIImage imageNamed:@"bg.png"]];
    UIView *labelContainer = [self.view viewWithTag:TAG_LABEL_CONTAINER_VIEW];
    UIView *textView = [self.view viewWithTag:TAG_TEXTVIEW];
    
    labelContainer.layer.cornerRadius = 8;
    labelContainer.layer.masksToBounds = YES;
    textView.layer.cornerRadius = 8;
    labelContainer.layer.masksToBounds = YES;
    
    [self initWithChargeParam:_chargeParam goodsInfo:_goodsInfo];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - charge 分为余额充值和银联充值
// 余额充值
- (void)requestBalanceCharge
{
    
   /* 请求地址: /ofcard.php
    请求参数: action  => online_order
    user_id  => 用户id
    version	 => 客户端版本号
    goods_id	 => 游戏ID（即商品ID） 6-7位数字
    goods_num  => 商品数量
    game_user_id => 游戏玩家帐号
    game_area  => 游戏所在区，无填空
    game_srv  =>  游戏所在服务器
    money =>   支付金额，用于校验
    */
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍后"];
    
    NSString *host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSString *urlStr = [host stringByAppendingString:@"ofcard.php"];
    
    static NSString *action = @"online_order";
   
    NSString *clientVersion = [[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil];
    NSString *userId = @"13811895850";
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSURL URLWithString:urlStr], @"requestBalanceFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:3];
    [param setObject:action forKey:@"action"];
    [param setObject:userId forKey:@"user_id"];
    [param setObject:clientVersion forKey:@"version"];
    [param setObject:_goodsInfo.cardId forKey:@"goods_id"];
    [param setObject:_chargeParam.goodsNum forKey:@"goods_num"];
    [param setObject:_chargeParam.userId forKey:@"game_user_id"];
    
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    if (_chargeParam.area) {
         [param setObject:_chargeParam.area forKey:@"game_area"];
    }
    
    if (_chargeParam.server) {
        [param setObject:_chargeParam.server forKey:@"game_srv"];
    }
    
    [param setObject:_chargeParam.money forKey:@"money"];

    [[app httpRequestPoint]openUrl:dic
                         postParam:param target:self];
}


- (void)requestBalanceFinished:(NSData *)response
{
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    NSLog(@"--------rootElement:%@", rootElement);
    GDataXMLElement *head = [[rootElement elementsForName:@"head"] objectAtIndex:0];
    GDataXMLElement *returncode = [[head elementsForName:@"returncode"] objectAtIndex:0];
    NSLog(@"--------returncode:%@", returncode);
    
    CHARGE_RESULT result = FAIL;
    if (returncode == 0) {
        result = SUCCESSFUL;
    }
    
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app hideProgressDialog];
    
    /*
     失败body为空，returncode为：
     'error_system'		=>	'-200',		//	=>系统错误 
     'error_action'		=>	'-100',		//	=>请求错误 
     'error_version'		=>	'-104',		//	=>版本错误
     'error_nologin'		=>	'-105',		//  =>未登录
     'error_uid'			=>  '-106',		//  =>uid非数
     'error_goodsid'		=>	'-117',		//	=>商品id
     'error_goodsnum'	=>	'-118',		//	=>商品数量
     'error_money'		=>  '-107',		//  =>错误钱
     */
    
    GameResultController *nextController = [[GameResultController alloc] initWithResult:result];
    
    [self.navigationController pushViewController:nextController animated:YES];
    [nextController release];
}

- (void) confirm:(id)sender
{
    [self requestBalanceCharge];
}

@end
